package com.fgsecure.apjhnou.app;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Vector;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.http.util.ByteArrayBuffer;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.fgsecure.apjhnou.adapter.CategoryAdapter;
import com.fgsecure.apjhnou.info.Global;
import com.fgsecure.apjhnou.quickactions.ActionItem;
import com.fgsecure.apjhnou.quickactions.QuickAction;

public class CategoryActivity extends Activity {
	private ListView listViewCategory;
	private Vector<Object> vCategory;
	final Context context = this;
	private static final int ID_UP = 1;
	private static final int ID_DOWN = 2;
	private static final int ID_NEW = 3;
	private static final int ID_EDIT = 4;
	private static final int ID_DEL = 5;
	private int positionLongClick = 0;
	private ProgressDialog pDialog;
	ImageView my_image;
	// Progress dialog type (0 - for Horizontal progress bar)
	public static final int progress_bar_type = 0;

	// File url to download
	private static String file_url = "http://dhm.edu.vn/hoclieu/chuong-1.zip";

	String[] values = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// OpenDialogLayout layoutfile = new OpenDialogLayout(context);
		// setContentView(layoutfile);
		setContentView(R.layout.main);
		initUI();
		initData();
	}

	public void initUI() {
		saveToSdcard("myFile.XML");
		listViewCategory = (ListView) findViewById(R.id.listViewCategory);
	}

	public void initData() {
		Vector<Object> menu = Global.readXML();
		vCategory = new Vector<Object>();
		values = new String[menu.size() / 2];
		Integer valuesNum = 0;
		for (int i = 0; i < menu.size(); i = i + 2) {
			values[valuesNum++] = (String) menu.get(i);
			Vector<Object> category = (Vector<Object>) menu.get(i + 1);
			vCategory.add(category);
		}
		CategoryAdapter adapter = new CategoryAdapter(this,
				R.layout.listview_item_row, values);
		View header = (View) getLayoutInflater().inflate(
				R.layout.listview_header_row, null);
		listViewCategory.addHeaderView(header);
		listViewCategory.setAdapter(adapter);
		final Intent intent = new Intent(this, SubjectActivity.class);
		// intent.putExtra("category", "CategoryActivity");
		ActionItem downItem = new ActionItem(ID_DOWN, "Download", getResources()
				.getDrawable(R.drawable.menu_down_arrow));
		ActionItem upItem = new ActionItem(ID_UP, "Up", getResources()
				.getDrawable(R.drawable.menu_up_arrow));
		ActionItem addItem = new ActionItem(ID_NEW, "New", getResources()
				.getDrawable(R.drawable.menu_add));
		ActionItem editItem = new ActionItem(ID_EDIT, "Edit", getResources()
				.getDrawable(R.drawable.menu_edit));
		ActionItem delItem = new ActionItem(ID_DEL, "Delete", getResources()
				.getDrawable(R.drawable.menu_del));
		// use setSticky(true) to disable QuickAction dialog being dismissed
		// after an item is clicked
		// upItem.setSticky(true);
		// downItem.setSticky(true);
		// create QuickAction. Use QuickAction.VERTICAL or
		// QuickAction.HORIZONTAL param to define layout
		// orientation
		final QuickAction quickAction = new QuickAction(this,
				QuickAction.HORIZONTAL);
		// add action items into QuickAction
		quickAction.addActionItem(downItem);
		// quickAction.addActionItem(upItem);
		quickAction.addActionItem(addItem);
		quickAction.addActionItem(editItem);
		quickAction.addActionItem(delItem);
		// Set listener for action item clicked
		quickAction
				.setOnActionItemClickListener(new QuickAction.OnActionItemClickListener() {
					@Override
					public void onItemClick(QuickAction source, int pos,
							int actionId) {
						ActionItem actionItem = quickAction.getActionItem(pos);
						// here we can filter which action item was clicked with
						// pos or actionId parameter
						if (actionId == ID_UP) {
							Toast.makeText(getApplicationContext(), "up",
									Toast.LENGTH_SHORT).show();
						} else if (actionId == ID_DOWN) {
							new DownloadFileFromURL().execute(file_url);
						} else if (actionId == ID_NEW) {
							dialogAdd();
						} else if (actionId == ID_EDIT) {
							if (positionLongClick != 0)
								dialogEdit();
						} else if (actionId == ID_DEL) {
							if (positionLongClick != 0)
								dialogDelete();
						}
					}
				});
		// set listnener for on dismiss event, this listener will be called only
		// if QuickAction dialog was dismissed
		// by clicking the area outside the dialog.
		quickAction.setOnDismissListener(new QuickAction.OnDismissListener() {
			@Override
			public void onDismiss() {
				// Toast.makeText(getApplicationContext(), "Dismissed",
				// Toast.LENGTH_SHORT).show();
			}
		});
		listViewCategory
				.setOnItemLongClickListener(new OnItemLongClickListener() {
					public boolean onItemLongClick(AdapterView<?> adapter,
							View view, int position, long id) {
						positionLongClick = position;
						quickAction.show(view);
						return false;
					}
				});
		listViewCategory.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Log.v("****************", position + "");
				if (position > 0) {
					// Global.setvObj(vSubject);
					Global.setCategory(position - 1);
					Vector<Object> menu = Global.readXML();
					Vector<Object> vSubject = (Vector<Object>) menu.get(Global
							.getCategory() * 2 + 1);
					Global.setvObj(vSubject);
					startActivity(intent);
				}
			}
		});
	}

	public void saveToSdcard(String fileName) {
		try {
			File root = android.os.Environment.getExternalStorageDirectory();
			File dir = new File(root.getAbsolutePath() + "/MyFile");
			if (dir.exists() == false) {
				dir.mkdirs();
			}
			File file = new File(dir, fileName);
			if (file.exists()) {
				// Do action
			} else {
				// InputStream is = ucon.getInputStream();
				InputStream is = getBaseContext().getResources()
						.openRawResource(R.raw.myxml);
				BufferedInputStream bis = new BufferedInputStream(is);
				// Read bytes to the Buffer until there is nothing more to
				// read(-1).
				ByteArrayBuffer baf = new ByteArrayBuffer(5000);
				int current = 0;
				while ((current = bis.read()) != -1) {
					baf.append((byte) current);
				}
				/* Convert the Bytes read to a String. */
				FileOutputStream fos = new FileOutputStream(file);
				fos.write(baf.toByteArray());
				fos.flush();
				fos.close();
			}
		} catch (IOException e) {
			Log.d("saveManager", "Error: " + e);
		}
	}

	public void addCategory(String name) throws ParserConfigurationException,
			SAXException, IOException, TransformerException {
		File fXmlFile = new File("/sdcard/MyFile/myFile.xml");
		DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder dBuilder = null;
		Document doc = null;
		dBuilder = dbFactory.newDocumentBuilder();
		doc = dBuilder.parse(fXmlFile);
		doc.getDocumentElement().normalize();
		Element root = doc.getDocumentElement();
		Element category = doc.createElement("category");
		category.setAttribute("name", name);
		root.appendChild(category);
		Log.v("--------------------------",
				"add element :" + category.getNodeName());
		// write the content into xml file
		TransformerFactory transformerFactory = TransformerFactory
				.newInstance();
		Transformer transformer = transformerFactory.newTransformer();
		DOMSource source = new DOMSource(doc);
		StreamResult result = new StreamResult(fXmlFile);
		transformer.transform(source, result);
	}

	public void delCategory() throws ParserConfigurationException,
			SAXException, IOException, TransformerException {
		File fXmlFile = new File("/sdcard/MyFile/myFile.xml");
		DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder dBuilder = null;
		Document doc = null;
		dBuilder = dbFactory.newDocumentBuilder();
		doc = dBuilder.parse(fXmlFile);
		doc.getDocumentElement().normalize();
		Element root = doc.getDocumentElement();
		NodeList nList = root.getElementsByTagName("category");
		Node nNode = nList.item(positionLongClick - 1);
		root.removeChild(nNode);
		// write the content into xml file
		TransformerFactory transformerFactory = TransformerFactory
				.newInstance();
		Transformer transformer = transformerFactory.newTransformer();
		DOMSource source = new DOMSource(doc);
		StreamResult result = new StreamResult(fXmlFile);
		transformer.transform(source, result);
	}

	public void editCategory(String name) throws ParserConfigurationException,
			SAXException, IOException, TransformerException {
		File fXmlFile = new File("/sdcard/MyFile/myFile.xml");
		DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder dBuilder = null;
		Document doc = null;
		dBuilder = dbFactory.newDocumentBuilder();
		doc = dBuilder.parse(fXmlFile);
		doc.getDocumentElement().normalize();
		Element root = doc.getDocumentElement();
		NodeList nList = root.getElementsByTagName("category");
		Node nNode = nList.item(positionLongClick - 1);
		Element eElement = (Element) nNode;
		eElement.setAttribute("name", name);
		// write the content into xml file
		TransformerFactory transformerFactory = TransformerFactory
				.newInstance();
		Transformer transformer = transformerFactory.newTransformer();
		DOMSource source = new DOMSource(doc);
		StreamResult result = new StreamResult(fXmlFile);
		transformer.transform(source, result);
	}

	private void restartFirstActivity() {
		Intent i = getApplicationContext().getPackageManager()
				.getLaunchIntentForPackage(
						getApplicationContext().getPackageName());
		i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivity(i);
	}

	public void dialogAdd() {
		// get prompts.xml view
		LayoutInflater li = LayoutInflater.from(context);
		View promptsView = li.inflate(R.layout.prompts_category, null);
		AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
				context);
		// set prompts.xml to alertdialog builder
		alertDialogBuilder.setView(promptsView);
		TextView typeText = (TextView) promptsView
				.findViewById(R.id.typeTextTextView);
		typeText.setText(context.getString(R.string.text_category));
		final EditText userInput = (EditText) promptsView
				.findViewById(R.id.editTextDialogUserInput);
		// set dialog message
		alertDialogBuilder
				.setCancelable(false)
				.setPositiveButton("OK", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						// get user input
						try {
							addCategory(userInput.getText().toString().trim());
						} catch (ParserConfigurationException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (SAXException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (TransformerException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

						restartFirstActivity();
					}
				})
				.setNegativeButton("Cancel",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								dialog.cancel();
							}
						});
		// create alert dialog
		AlertDialog alertDialog = alertDialogBuilder.create();
		// show it
		alertDialog.show();
	}

	public void dialogDelete() {
		// get prompts.xml view
		LayoutInflater li = LayoutInflater.from(context);
		View promptsView = li.inflate(R.layout.prompts_delete, null);
		AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
				context);
		// set prompts.xml to alertdialog builder
		alertDialogBuilder.setView(promptsView);
		TextView typeText = (TextView) promptsView
				.findViewById(R.id.itemDelTextView);
		typeText.setText(values[positionLongClick - 1]);
		// set dialog message
		alertDialogBuilder
				.setCancelable(false)
				.setPositiveButton("OK", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						// get user input
						try {
							delCategory();
						} catch (ParserConfigurationException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (SAXException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (TransformerException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

						restartFirstActivity();
					}
				})
				.setNegativeButton("Cancel",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								dialog.cancel();
							}
						});
		// create alert dialog
		AlertDialog alertDialog = alertDialogBuilder.create();
		// show it
		alertDialog.show();
	}

	public void dialogEdit() {
		// get prompts.xml view
		LayoutInflater li = LayoutInflater.from(context);
		View promptsView = li.inflate(R.layout.prompts_category, null);
		AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
				context);
		// set prompts.xml to alertdialog builder
		alertDialogBuilder.setView(promptsView);
		TextView typeText = (TextView) promptsView
				.findViewById(R.id.typeTextTextView);
		typeText.setText(context.getString(R.string.text_category));
		final EditText userInput = (EditText) promptsView
				.findViewById(R.id.editTextDialogUserInput);
		userInput.setText(values[positionLongClick - 1]);
		userInput.selectAll();
		// set dialog message
		alertDialogBuilder
				.setCancelable(false)
				.setPositiveButton("OK", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						// get user input
						try {
							editCategory(userInput.getText().toString().trim());
						} catch (ParserConfigurationException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (SAXException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (TransformerException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

						restartFirstActivity();
					}
				})
				.setNegativeButton("Cancel",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								dialog.cancel();
							}
						});
		// create alert dialog
		AlertDialog alertDialog = alertDialogBuilder.create();
		// show it
		alertDialog.show();
	}

	/**
	 * Showing Dialog
	 * */
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case progress_bar_type:
			pDialog = new ProgressDialog(this);
			pDialog.setMessage("Downloading file. Please wait...");
			pDialog.setIndeterminate(false);
			pDialog.setMax(100);
			pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			pDialog.setCancelable(false);
			pDialog.show();
			return pDialog;
		default:
			return null;
		}
	}

	/**
	 * Background Async Task to download file
	 * */
	class DownloadFileFromURL extends AsyncTask<String, String, String> {

		/**
		 * Before starting background thread Show Progress Bar Dialog
		 * */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			showDialog(progress_bar_type);
		}

		/**
		 * Downloading file in background thread
		 * */
		@Override
		protected String doInBackground(String... f_url) {
			int count;
			try {
				URL url = new URL(f_url[0]);
				URLConnection conection = url.openConnection();
				conection.connect();
				// getting file length
				int lenghtOfFile = conection.getContentLength();

				// input stream to read file - with 8k buffer
				InputStream input = new BufferedInputStream(url.openStream(),
						8192);

				// Output stream to write file
				OutputStream output = new FileOutputStream(
						"/sdcard/MyFile/chuong-1.zip");

				byte data[] = new byte[1024];

				long total = 0;

				while ((count = input.read(data)) != -1) {
					total += count;
					// publishing the progress....
					// After this onProgressUpdate will be called
					publishProgress("" + (int) ((total * 100) / lenghtOfFile));

					// writing data to file
					output.write(data, 0, count);
				}

				// flushing output
				output.flush();

				// closing streams
				output.close();
				input.close();

			} catch (Exception e) {
				Log.e("Error: ", e.getMessage());
			}

			return null;
		}

		/**
		 * Updating progress bar
		 * */
		protected void onProgressUpdate(String... progress) {
			// setting progress percentage
			pDialog.setProgress(Integer.parseInt(progress[0]));
		}

		/**
		 * After completing background task Dismiss the progress dialog
		 * **/
		@Override
		protected void onPostExecute(String file_url) {
			// dismiss the dialog after the file was downloaded
			dismissDialog(progress_bar_type);
			String file_path = "/MyFile/chuong-1.zip";
			new UnzipFile().execute(file_path);
		}

	}
	class UnzipFile extends AsyncTask<String, String, String> {

		/**
		 * Before starting background thread Show Progress Bar Dialog
		 * */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(context);
			pDialog.setMessage("Unziping file. Please wait...");
			pDialog.setIndeterminate(false);
			pDialog.setMax(100);
			pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			pDialog.setCancelable(false);
			pDialog.show();
//			showDialog(progress_bar_type);
		}

		/**
		 * Downloading file in background thread
		 * */
		@Override
		protected String doInBackground(String... f_url) {
			int count;
			try {
				String path = f_url[0];
				 String zipFile = Environment.getExternalStorageDirectory()
				 + path;
				 String unzipLocation = Environment.getExternalStorageDirectory()
				 + "/hoclieu/";
				 Decompress d = new Decompress(zipFile, unzipLocation);
				 d.unzip();
				

			} catch (Exception e) {
				Log.e("Error: ", e.getMessage());
			}

			return null;
		}

		/**
		 * Updating progress bar
		 * */
		protected void onProgressUpdate(String... progress) {
			// setting progress percentage
			pDialog.setProgress(Integer.parseInt(progress[0]));
		}

		/**
		 * After completing background task Dismiss the progress dialog
		 * **/
		@Override
		protected void onPostExecute(String file_url) {
			// dismiss the dialog after the file was downloaded
			pDialog.dismiss();		
		}

	}
}